package com.yb.forum.services.impl;

import com.yb.forum.common.AppResult;
import com.yb.forum.common.ResultCode;
import com.yb.forum.dao.BoardMapper;
import com.yb.forum.exception.ApplicationException;
import com.yb.forum.model.Board;
import com.yb.forum.services.IBoardService;
import com.yb.forum.utils.RedisCacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class BoardServiceImpl implements IBoardService {

    @Resource
    private BoardMapper boardMapper;

    @Resource
    private RedisCacheUtil redisCacheUtil;

    private static final String BOARD_LIST_CACHE_PREFIX = "board:list:num:";
    private static final String BOARD_CACHE_PREFIX_BY_ID = "board:id:";
    private static final long CACHE_EXPIRE_SECONDS = 3600;

    @Override
    public List<Board> selectByNum(Integer num) {
        if (num == null || num <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        String cacheKey = BOARD_LIST_CACHE_PREFIX + num;
        List<Board> result = redisCacheUtil.getCacheList(cacheKey, Board.class);

        if (result != null) {
            log.debug("从 Redis 缓存获取版块列表: num={}", num);
            return result;
        }

        result = boardMapper.selectByNum(num);
        if (result == null) {
            result = Collections.emptyList();
        }

        redisCacheUtil.setCacheList(cacheKey, result, CACHE_EXPIRE_SECONDS, TimeUnit.SECONDS);
        log.debug("从数据库加载版块列表并缓存: num={}", num);
        return result;
    }

    @Override
    public Board selectById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }

        String cacheKey = BOARD_CACHE_PREFIX_BY_ID + id;
        Board board = redisCacheUtil.getCacheObject(cacheKey, Board.class);

        if (board != null) {
            log.debug("从 Redis 缓存获取版块: id={}", id);
            return board;
        }

        board = boardMapper.selectByPrimaryKey(id);
        if (board != null) {
            redisCacheUtil.setCacheObject(cacheKey, board, CACHE_EXPIRE_SECONDS, TimeUnit.SECONDS);
            log.debug("从数据库加载版块并缓存: id={}", id);
        }
        return board;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }

        Board current = boardMapper.selectByPrimaryKey(id);
        if (current == null) {
            log.warn(ResultCode.ERROR_IS_NULL.toString() + "board_id is " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }

        Board updateBoard = new Board();
        updateBoard.setId(id);
        updateBoard.setArticleCount(current.getArticleCount() + 1);

        int rows = boardMapper.updateByPrimaryKeySelective(updateBoard);
        if (rows != 1) {
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }

        // 更新成功后，清除对应缓存
        String cacheKey = BOARD_CACHE_PREFIX_BY_ID + id;
        redisCacheUtil.delete(cacheKey);

        log.debug("版块帖子数更新成功并清除缓存: id={}", id);
    }
}